import { formatGMTDate, compareObject, toPercent, biColors} from '../../../../assets/js/util.js'
import advance from '../advancedFilter.vue'
import echarts from 'echarts'
export default {
    data() {
        return {
            // 默认参数 和 URL
            SRC: '',
            DP: {
                p: '',
                f: ''
            },
            // title
            title: "新增用户",
            xlsxTitle:'',
            xlsxTitleQ:'',            
            /* 的宽*/
            pageWidth: '100%',
            /*当前页显示数量*/
            pageSize: 10,
            /*每页显示的数量*/
            pageSizes: [10, 20, 50, 100],
            /*dataTotal表数量*/
            dataTotal: 0,
            /*分页器*/
            currentPage: 1,
            /*当前页显示数量*/
            pageSize2: 10,
            /*每页显示的数量*/
            pageSizes2: [10, 20, 50, 100],
            /*dataTotal表数量*/
            dataTotal2: 0,
            /*分页器*/
            currentPage2: 1,
            // 选择的时间
            date: '',
            // 渠道数组
            plats: [],
            // 渠道数组
            channels: [],
            // 服务器数组
            servers: [],
            // 默认选择 在线趋势 PCU
            activeIndex: '1',
            activeIndex2: '1',
            // 默认的一些时间范围
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近15天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }],
                disabledDate(time) {
                    return time.getTime() > Date.now() - 8.64e7;
                }
            },
            // 新增概况数据指标说明：
            introduce1: [
                {
                    title: "设备激活",
                    message: "首次启动游戏的设备数（按历史取所有设备的最早启动时间）"
                },
                {
                    title: "激活新增转化率",
                    message: "首次登录游戏的设备数（按历史取所有设备的最早登录时间）/首次启动游戏的设备数（按历史取所有设备的最早启动时间）"
                },
                {
                    title: "新增玩家",
                    message: "首次登录游戏的账号数（按历史取所有账号的最早登录时间）"
                },
                {
                    title: "新增设备",
                    message: "首次登录游戏的设备数（按历史取所有设备的最早登录时间）"
                }
            ],
            postObj: {
                dstart: '',
                dend: '',
                platform: '0',
                channel: '0',
                server: '0'
            },
            // 后台请求回来的全部数据
            dataAll: null,
            // 新增概况详细数据 表头
            tableHeader: [{
                prop: 'day',
                label: '日期',
                width: '160px'
            }, {
                prop: 'activeDevice',
                label: '设备激活',
                width: 'auto'
            }, {
                prop: 'newDevice',
                label: '设备新增',
                width: 'auto'
            }, {
                prop: 'active2NewRadio',
                label: '激活-新增转化率（设备）',
                width: 'auto'
            }, {
                prop: 'newUser',
                label: '新增玩家',
                width: 'auto'
            }],
            // 新增玩家渠道详细数据 表头
            tableHeader2: [{
                prop: 'day',
                label: '日期',
                width: '160px'
            }],
            tableData: [],
            tableDataAll: [],
            tableData2: [],
            tableDataAll2: [],
            // 图表数据
            real: {
                color:biColors,
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['1']
                },
                grid: {
                    left: '1%',
                    right: '2%',
                    bottom: '15%',
                    containLabel: true
                },
                toolbox: {
                    right: '20',
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        magicType: {
                            type: ['line', 'bar']
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    data: [],
                    axisLabel: {
                        margin: 20,
                    },
                },
                yAxis: {
                    type: 'value',
                    // max: 10000
                },
                dataZoom: [{
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }],
                series: [
                ]
            },
            // 存储数据
            chartData: [],
        }
    },
    methods: {
        //初始化
        _init() {
            window.addEventListener('resize', function() {
                this.realTimeDataChart.resize();
                this.realTimeDataChart2.resize()
            }.bind(this))
        },
        // 表格下载
        excel(tableIndex, sheet) {
            var that = this;
            if(that.postObj.platform=="0"){
                that.xlsxTitleQ = "全平台";
            }else if(that.postObj.platform=="3"){
                that.xlsxTitleQ = "安卓";
            }else if(that.postObj.platform=="2"){
                that.xlsxTitleQ = "ios";
            }else if(that.postObj.platform=="9"){
                that.xlsxTitleQ = "通用";
            }
            that.xlsxTitle = sheet+"-"+that.xlsxTitleQ+"-"+that.postObj.dstart+"到"+that.postObj.dend;
            that.downloadExl(that["tableHeader"+tableIndex], that["tableDataAll"+tableIndex],that.xlsxTitle,sheet);
            
        },
        // 通用 成功 与 失败
        successFun(data) {
            this.$message({
                message: data,
                type: 'success'
            });
        },
        errorFun(data) {
            this.$message.error(data);
        },
        // 时间改变 得到起始时间和结束时间
        dateChange(val) {
            if (val === undefined) {
                this.errorFun('请选择查看时间！')
            } else {
                var t = val.split(' - ')
                this.postObj.dstart = t[0];
                this.postObj.dend = t[1];
                if (t[0] > t[1]) {
                    this.errorFun('开始日期不能大于结束日期，请您重新选择日期！')
                } else {
                    if (this.tableDataAll.length > 0) {
                        this.getData(this.postObj);
                    }
                }
            }
        },
        // 分页器
        // 控制每页的数量
        handleSizeChange(val) {
            this.pageSize = val;
            this.tableControl();
        },
        // 页数
        handleCurrentChange(val) {
            this.currentPage = val;
            this.tableControl();
        },
        tableControl() {
            this.tableData = this.tableDataAll.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
        },
        // 控制每页的数量
        handleSizeChange2(val) {
            this.pageSize2 = val;
            this.tableControl2();
        },
        // 页数
        handleCurrentChange2(val) {
            this.currentPage2 = val;
            this.tableControl2();
        },
        tableControl2() {
            this.tableData2 = this.tableDataAll2.slice((this.currentPage2 - 1) * this.pageSize2, this.currentPage2 * this.pageSize2)
        },
        // 选择游戏的平台
        handleSelect(key, keyPath) {
            if (key === '4') {
                this.$refs.advance.filterShow = true;
                return
            }
            if (this.postObj['server'] === '0' && this.postObj['channel'] === '0') {
                this.postObj['server'] = '0';
                this.postObj['channel'] = '0';
                this.postObj['platform'] = key;
                this.getList('updatePlatform', `platform=${key}`);
                this.getData(this.postObj);
            } else {
                if (key === "3" || key === "2" || key === "9") {
                    this.errorFun("请修改为全渠道和全服！")
                }
            }
        },
        //新增概况 菜单变换  
        handle(key, keyPath) {
            var setColor = '';
            switch (key) {
                case '1':
                    this.activeIndex2="1";
                    break;
                case '2':
                    this.activeIndex2="2";
                    break;
            }
            this.echartsChange(this.activeIndex2);
        },
        // 通过菜单的变换来判断渲染的数据是那个图表的
        echartsChange(num){
            if(num==="1"){
                this.echartsDataDevice(this.dataAll);
            }else if(num==="2"){
                this.echartsDataUser(this.dataAll);
            }
        },
        // 获取服务器list 平台list  服务器list
        getList(url, choose) {
            var that = this;
            var pushData = function(pushArr, attr, data) {
                that[pushArr] = [];
                for (var i in data[attr]) {
                    that[pushArr].push({
                        value: i,
                        label: data[attr][i]
                    })
                }
            };
            this.$http.jsonp(`${that.SRC}data/get.do?p=${that.DP.p}&f=${that.DP.f}&a=${url}`, {
                params: { 'ps': choose }
            }).then(function(res) {
                var data = JSON.parse(JSON.parse(res.body));
                if (parseInt(data["res"]) === 0) {
                    // 后台select的数据
                    var lists = ["platformItmes", "channelItmes", "serverItmes"];
                    // 页面select名字
                    var nameLists = ["plats", "channels", "servers"];
                    for (var i = 0; i < lists.length; i++) {
                        if (data[lists[i]] !== undefined) {
                            pushData(nameLists[i], lists[i], data);
                        }
                    }
                } else {
                    // this.getErrorMsg(Number(data.res))
                }
            })
        },
        // 小数转化为百分数
        pencent(data) {
            //转换为%比 
            for (var i = 0; i < data.length; i++) {
                for (var j in data[i]) {
                    if (j === 'active2NewRadio') {
                        data[i][j] = toPercent(data[i][j]);
                    }
                }
            }
            return data
        },
        // 获取数据
        getData(data) {
            var that = this;
            var p = new Promise(function(resolve, reject) {
                that.dataTotal = 0;
                that.loading = true;
                that.tableData = [];
                that.tableDataAll = [];
                that.$http.jsonp(`${that.SRC}data/get.do?p=${that.DP.p}&f=${that.DP.f}&a=search`, {
                    params: { 'ps': `dstart=${data.dstart}&dend=${data.dend}&platform=${data.platform}&channel=${data.channel}&server=${data.server}` }
                }).then(function(res) {
                    resolve(res.body)
                })
            })
            p.then(function(value) {
                that.loading = false;
                var data = JSON.parse(value)
                var d = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                if (parseInt(d["res"]) === 0) {
                    that.dataAll = d;
                    that.tableHeadFun(d.newPlayerByChannelDatas);
                    that.dataTotal = d.newPlayerDatas.length;
                    that.tableDataAll = that.pencent(d.newPlayerDatas);
                    that.tableControl();
                    that.echartsChange(that.activeIndex2);
                    that.echartsDataChannel(d);
                } else {
                    that.errorFun(data["msg"])
                }
            })
        },
        // 新增概况-设备相关请求回来的数据进行整理
        echartsDataDevice(d) {
            if (d.deviceActiveChart === undefined) {
                var data = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
            } else {
                var data = d['deviceActiveChart']['jsonStr'];
            }
            if (d.deviceActive2NewChart === undefined) {
                var data1 = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
            } else {
                var data1 = d['deviceActive2NewChart']['jsonStr'];
            }

            this.realTimeDataChart.setOption({
                legend: {
                    data: [data['names'][0],data1['names'][0]]
                },
                xAxis: {
                    data: data.columnkeys
                },
                grid: {
                    top:"20%",
                    left: '1%',
                    right: '2%',
                    bottom: '15%',
                    containLabel: true
                },
                dataZoom: [{
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }],
                tooltip: {
                    trigger: 'axis',
                    formatter: function(a) {
                        var temp = '';
                        for (var i = 0, len = a.length; i < len; i++) {
                            if (a[i].seriesName.indexOf("转化率") < 0) {
                                var str = '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + "#2eb398" + '"></span>';
                                temp = str + temp + a[i].seriesName + '：' + a[i].value + '</br>';
                            } else {
                                var str = '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + "#9d79d8" + '"></span>';
                                temp = temp + str + a[i].seriesName + '：' + Number(a[i].value * 100).toFixed(2) + '%' + '</br>';
                            }
                        }
                        return "日期：" + a[0].name + '</br>' + temp;
                    }
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '数量',
                        axisLabel: {
                            formatter: function(value) {
                                value = value / 1000;
                                return value + "k";
                            }
                        },
                        axisLine: {
                            lineStyle: {
                                color: '#2eb398'
                            }
                        }
                    },
                    {
                        type: 'value',
                        name: '占比(%)',
                        splitLine: { show: false },
                        axisLabel: {
                            formatter: function(value) {
                                if (typeof(value) == "number") {
                                    var str = (value * 100).toFixed(0);
                                } else {
                                    var str = Number(value * 100).toFixed(0)
                                }
                                str += "%";
                                return str;
                            }
                        },
                        axisLine: {
                            lineStyle: {
                                color: '#9d79d8'
                            }
                        }
                    }
                ],
                toolbox: {
                    right: '20',
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        magicType: {
                            type: ['line', 'bar']
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                series: [
                    {
                        type: 'line',
                        name: data.names[0],
                        yAxisIndex: 0,
                        data: data.data[0],
                        barMaxWidth: '50',
                        smooth: true,
                        itemStyle: {
                            normal: {
                                color: '#2eb398'
                            }
                        },
                    },
                    {
                        type: 'bar',
                        barMaxWidth: '50',
                        name: data1.names[0],
                        yAxisIndex: 1,
                        data: data1.data[0],
                        itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#b8cff1' },
                                    { offset: 0.5, color: '#a99ce4' },
                                    { offset: 1, color: '#a07cdc' }
                                ]
                            )
                        },
                        emphasis: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#a07cdc' },
                                    { offset: 0.7, color: '#a99ce4' },
                                    { offset: 1, color: '#b8cff1' }
                                ]
                            )
                        }
                    }
                    }
                ]
            }, true);
        },
        // 新增概况-账号相关请求回来的数据进行整理
        echartsDataUser(d){
            if (d.userNewChart === undefined) {
                var data = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
            } else {
                var data = d['userNewChart']['jsonStr'];
            }

            this.realTimeDataChart.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    data: data.columnkeys
                },
                grid: {
                    left: '1%',
                    right: '2%',
                    bottom: '15%',
                    containLabel: true
                },
                dataZoom: [{
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }],
                tooltip: {
                    trigger: 'axis'
                },
                yAxis: {
                    type: 'value',
                    // max: 10000
                },
                toolbox: {
                    right: '20',
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        magicType: {
                            type: ['line', 'bar']
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                series: [
                    {
                        type: 'line',
                        name: data.names[0],
                        yAxisIndex: 0,
                        data: data.data[0],
                        barMaxWidth: '50',
                        smooth: true,
                        itemStyle: {
                            normal: {
                                color: '#2eb398'
                            }
                        },
                    }
                ]
            }, true);
        },
        echartsDataChannel(d) {
            if (d.userNewByChannelChart === undefined) {
                var data2 = {
                    "columnkeys": [],
                    "names": [],
                    "data": [
                        []
                    ]
                }
            } else {
                var data2 = d['userNewByChannelChart']['jsonStr'];
            }
            var seriesArr = [];
            for(var i=0; i<data2.data.length; i++){
                var obj = {
                    smooth: true,
                    type: 'line',
                    name: data2.names[i],
                    data: data2.data[i]
                }
                seriesArr.push(obj);
            }
            this.realTimeDataChart2.setOption({
                grid: {
                    left: '1%',
                    right: '2%',
                    top: '20%',
                    containLabel: true
                },
                legend: {
                    width: "80%",
                    top: '10',
                    left: "30",
                    data: data2['names']
                },
                xAxis: {
                    boundaryGap: true,
                    data: data2.columnkeys
                },
                series: seriesArr
            });
        },
        // 表格排序
        sortChange(column) {
            if (column.prop === null) {
                return;
            } else if (column.order === 'descending') {
                this.tableDataAll.sort(compareObject(column.prop, false));
            } else { //正序
                this.tableDataAll.sort(compareObject(column.prop, true));
            }
            this.tableControl();
        },
        // 初始化详细数据表头
        tableHeadFun(d) {
            var arr = [],hash={};
            for(var i=0; i<d.length; i++){
                var elem = d[i]["channelId"];
                if(!hash[elem]){
                    var obj = {
                        prop : d[i]["channelId"],
                        label : d[i]["channelName"],
                        width : d[i]["channelName"].length>4?"160px":"120px"
                    }
                    arr.push(obj)
                    hash[elem] = true;
                }
            }
            this.tableHeader2 = arr;
            this.tableHeader2.unshift({
                prop: 'day',
                label: '日期',
                width: '160px',
                fixed: true
            });
            this.tableDataFun(d,arr)
        },
        tableDataFun(d,arr){
            var dataArr =[], hash = {};
            for(var i=0; i<d.length; i++){
                var date = d[i]["day"];
                if(!hash[d[i]["day"]]){
                    var obj = {
                       day : date
                    }
                    dataArr.push(obj)
                    hash[d[i]["day"]] = true;
                }
            }
            for(var j=0; j<d.length; j++){
                for(var n=0; n<dataArr.length; n++){
                    if(dataArr[n].day === d[j].day){
                        dataArr[n][d[j]["channelId"]] = d[j]["newUser"];
                    }
                }
            } 
            this.dataTotal2 = dataArr.length;
            this.tableDataAll2 = dataArr;
            this.tableControl2();
        }
        
    },
    components: {
        'v-advance': advance
    },
    computed: {
        // xlsx() {
        //     return this.title + '.xlsx'
        // }
    },
    mounted() {
        // 初始化URL
        this.SRC = this.$store.getters.src;
        this.DP.p = localStorage.getItem('ZULONGBIPROJECTID');
        this.DP.f = localStorage.getItem('ZULONGBIPAGEID');
        this.date = [new Date(new Date().getTime() - 7 * 86400000), new Date(new Date().getTime() - 86400000)];
        this.postObj.dstart = formatGMTDate(new Date() - 86400000 * 7, true);
        this.postObj.dend = formatGMTDate(new Date() - 86400000, true);
        // 获取到服务器 平台 渠道 list
        this.getList("initParam", "");
        // 实时图
        this.realTimeDataChart = echarts.init(document.getElementById('realTimeData'));
        this.realTimeDataChart.setOption(this.real);
        // 数据对比
        this.realTimeDataChart2 = echarts.init(document.getElementById('realTimeData2'));
        this.realTimeDataChart2.setOption(this.real);
        // 请求数据
        this.getData(this.postObj);

        this._init();
    }
}